package com.icesoft.core.web.suppose.sms.config;

import com.icesoft.core.web.model.SmsCodeDTO;
import org.springframework.cache.jcache.JCacheCacheManager;
import org.springframework.stereotype.Component;

import javax.cache.Cache;
import javax.cache.configuration.MutableConfiguration;
import javax.cache.expiry.CreatedExpiryPolicy;
import javax.cache.expiry.Duration;
import java.util.concurrent.TimeUnit;

@Component
public class SmsCodeCacheService {
    private static final long expiredTimeMill = 5;

    private Cache<String, SmsCodeDTO> cache;
    private static final String CACHE_NAME = "icesoft.smsCode.5m.key";

    public SmsCodeCacheService(JCacheCacheManager jCacheCacheManager) {
        MutableConfiguration defaultCacheConfiguration = new MutableConfiguration<>();
        defaultCacheConfiguration
                .setExpiryPolicyFactory(CreatedExpiryPolicy.factoryOf(new Duration(TimeUnit.MINUTES, expiredTimeMill)));
        cache = jCacheCacheManager.getCacheManager().createCache(CACHE_NAME, defaultCacheConfiguration);
    }

    public SmsCodeDTO getCache(String phone) {
        return cache.get(phone);
    }

    public void putCache(String phone, SmsCodeDTO smsCodeDTO) {
        cache.put(phone, smsCodeDTO);
    }

    public void remove(String phone) {
        cache.remove(phone);
    }

    public boolean check(String phone, String smsCode) {
        SmsCodeDTO cacheSmsCode = getCache(phone);
        if (cacheSmsCode == null) {
            return false;
        }
        // 验证码校验
        if (!cacheSmsCode.getCode().equalsIgnoreCase(smsCode)) {
            return false;
        }
        return true;
    }
}
